import AttrEle from './AttrEle'

export default class FormEle extends AttrEle {
    constructor (subject, ele) {
        super(subject, ele)
        this.model = ele.getAttribute('model')
        this.subject.subscribe(this.model, this)
    }
    drawInput() {
        let tagName = this.ele.tagName.toLowerCase()
        let target_model = this.subject.find_var(this.model)
        let dValue = (new Function('return ' + target_model)).call(this.subject)
        if(tagName == 'input'){
            let itype = this.ele.getAttribute('type')
            if(itype == 'checkbox'){
                if(typeof(dValue) == 'object' &&
                    Object.prototype.toString.call(dValue).toLowerCase() == '[object array]'){
                    if(dValue.indexOf(this.ele.value) != -1){
                        this.ele.checked = true;
                    }else{
                        this.ele.checked = false;
                    }
                }else{
                    if(dValue == this.ele.value){
                        this.ele.checked = true;
                    }else{
                        this.ele.checked = false;
                    }
                }
            }else if(itype == 'radio'){
                if(dValue == this.ele.value){
                    this.ele.checked = true;
                }else{
                    this.ele.checked = false;
                }
            }else{
                this.ele.value = dValue;
            }
        }else if(tagName == 'select'){
            let options = this.ele.options;
            for(let i = 0,len = options.length;i < len;i++){
                if(options[i].value == dValue){
                    options[i].selected = true;
                }else{
                    options[i].selected = false;
                }
            }
        }else if(tagName == 'textarea'){
            this.ele.innerHTML = dValue;
        }
    }
    draw (){
        super.draw()
        this.drawInput()
    }
    update (ev) {
        super.update(ev)
        if (ev == this.model) {
            this.drawInput()
        }
    }

}